package com.sam.im.heiqun.uis.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.FriendAdpter;
import com.sam.im.heiqun.uis.dialogs.MyAlertDialogManages;
import com.sam.im.heiqun.uis.widgets.sidebar.CharacterParserUtil;
import com.sam.im.heiqun.uis.widgets.sidebar.CountryComparator;
import com.sam.im.heiqun.uis.widgets.sidebar.CountrySortModel;
import com.sam.im.heiqun.uis.widgets.sidebar.GetCountryNameSort;
import com.sam.im.heiqun.uis.widgets.sidebar.SideBar;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.DividerItemDecorationUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangguodong on 2017/1/9.
 */
public class SelecteGroupFriendActivity extends BaseSwipeBackActivity implements FriendAdpter.FriendListClickListener, TextWatcher {
    private static final String TAG = SelecteGroupFriendActivity.class.getSimpleName();
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.list_friend)
    RecyclerView list_friend;
    @BindView(R.id.friend_dialog)
    TextView friend_dialog;
    @BindView(R.id.friend_sidebar)
    SideBar friend_sidebar;
    @BindView(R.id.ok)
    TextView ok;
    @BindView(R.id.search_edit)
    EditText search_edit;
    @BindView(R.id.swipe_refresh_widget)
    SwipeRefreshLayout swipeRefreshLayout ;
    private List<ImFriendEntivity> mBFriends;
    PGService mPgService;
    String uid = "";
    String uhead = "";
    private int type = 0;//判断是否是创建群组使用，0-是；1-不是
    private int goGroup = 0;//判断是否是通过好友详情页过来的，1-是；0-不是

    private List<CountrySortModel> mFriends;
    private CountryComparator pinyinComparator;
    /**
     * 获取字符串缩写
     */
    private CharacterParserUtil characterParserUtil;
    /**
     * 获取首字母
     */
    private GetCountryNameSort countryChangeUtil;
    private FriendAdpter mAdapter;
    private List<ImFriendEntivity> mFriendEntivities = new ArrayList<>();

    public static final int SELECT_FRIEND_IDS_FOR_RESULT = 1000 ;

    @Override
    public int getContentViewId() {
        return R.layout.activity_selecte_groupfriend;
    }


    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.selecte_group_friend);
    }

    public static void startActivity(Activity activity, int type, int goGroup){
        Intent intent = new Intent(activity,SelecteGroupFriendActivity.class);
        intent.putExtra("type",type);
        intent.putExtra("goGroup",goGroup);
        activity.startActivityForResult(intent, SELECT_FRIEND_IDS_FOR_RESULT);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        type = getIntent().getIntExtra("type", 0);
        goGroup = getIntent().getIntExtra("goGroup", 0);
        ok.setVisibility(View.VISIBLE);
        mPgService = PGService.getInstance();
        swipeRefreshLayout.setRefreshing(false);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        mFriendEntivities = (List<ImFriendEntivity>) getIntent().getSerializableExtra("mFriendEntivities");
        initView();
    }


    private void initData() {
        mFriends = new ArrayList<>();
        for (int i = 0; i < mBFriends.size(); i++) {
            if (null == mFriendEntivities || mFriendEntivities.size() == 0) {
                mFriends.add(ToolsUtils.changeFriendEntvity(mBFriends.get(i), characterParserUtil, countryChangeUtil));
            } else {
                boolean isZai = false;
                int size = mFriendEntivities.size();
                Log.e(TAG, "initData: size------" + size);
                for (int j = 0; j < size; j++) {
                    String friendEntityId = mFriendEntivities.get(j).getCurrentid() + "";
                    String mBId = mBFriends.get(i).getId() + "";
                    Log.e(TAG, "initData:  friendId---" + friendEntityId + "--mBid---" + mBId);
                    if (friendEntityId.equals(mBId)) {
                        isZai = true;
                        break;
                    }
                }
                if (!isZai) {
                    mFriends.add(ToolsUtils.changeFriendEntvity(mBFriends.get(i), characterParserUtil, countryChangeUtil));
                }
            }
        }
        Collections.sort(mFriends, pinyinComparator);//根据首字母进行排序
        mAdapter.refresh(mFriends);

    }

    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_DOWN) {
                String str = search_edit.getText().toString().trim();
                if (null != str && !"".equals(str.toString())) {
                    mBFriends = new ArrayList<>();
                    List<ImFriendEntivity> mBFriendsm = ImFriendEntivity.find(ImFriendEntivity.class, "currentid=? and is_black=?", ToolsUtils.getMyUserId(), "0");
                    if (null != mBFriendsm && mBFriendsm.size() > 0) {
                        for (int i = 0; i < mBFriendsm.size(); i++) {
                            if (mBFriendsm.get(i).getMobile().contains(str) || mBFriendsm.get(i).getRemark().contains(str) ||
                                    mBFriendsm.get(i).getName().contains(str) || mBFriendsm.get(i).getNickName().contains(str)) {
                                mBFriends.add(mBFriendsm.get(i));
                            }
                        }
                    }
                    initData();
                } else {
//                        showToast("什么鬼啊");
                }
                return true;
            }
            return false;
        }
    };

    private void initView() {
        /** 右侧字母栏*/
        friend_sidebar.setVisibility(View.GONE);//隐藏
//        friend_sidebar.setTextView(friend_dialog);
        pinyinComparator = new CountryComparator();
        countryChangeUtil = new GetCountryNameSort();
        characterParserUtil = new CharacterParserUtil();
        search_edit.addTextChangedListener(this);
        if (0==type){
            tvTitle.setText(getResources().getString(R.string.add_group_pers));
//            ok.setBackgroundResource(R.drawable.shape_nosure_bt);
            ok.setEnabled(false);
        }else {
            tvTitle.setText(getResources().getString(R.string.select_friend));
        }
        // 右侧sideBar监听
        friend_sidebar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    //这个设置的方式不是很准确流畅
                    list_friend.getLayoutManager().scrollToPosition(position);
                }
            }
        });
        /** 右侧字母栏 */

        list_friend.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        mFriends = new ArrayList<>();
        mAdapter = new FriendAdpter(getApplicationContext(), mFriends, 1);
        mAdapter.setItemClickListener(this);
        mAdapter.setHintHeadview(true);
        list_friend.setAdapter(mAdapter);
        list_friend.addItemDecoration(new DividerItemDecorationUtils(getApplicationContext(), LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.black_divider)));

        search_edit.setOnKeyListener(onKeyListener);

        mBFriends = ImFriendEntivity.find(ImFriendEntivity.class, "currentid=? and is_black=?", ToolsUtils.getMyUserId(), "0");
        initData();
        // 将联系人进行排序，按照A~Z的顺序
//        Collections.sort(mFriends, pinyinComparator);
    }

    @Override
    public void onAgreeNewFriendClick(View view, int position) {
        int num = position -1 ;
        if (mFriends.get(num).isSelecte) {
            mFriends.get(num).isSelecte = false;
        } else {
            mFriends.get(num).isSelecte = true;
        }
        mAdapter.refresh(mFriends);
        if (0==type){
            boolean isselected = false ;
            for (int f = 0; f < mFriends.size(); f++) {
                boolean selecte = mFriends.get(f).isSelecte;
                Log.i("info","selecte=="+selecte);
                if (selecte){
                    isselected = true ;
                    break;
                }
            }
            if (isselected){
                ok.setEnabled(true);
//                ok.setBackgroundResource(R.drawable.shape_sure_bt);
            }else {

                ok.setEnabled(false);
//                ok.setBackgroundResource(R.drawable.shape_nosure_bt);
            }

        }
    }

    @OnClick({R.id.ok, R.id.pre_v_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                scrollToFinishActivity();
                break;
            case R.id.ok:
                if (null != mFriends && mFriends.size() > 0) {
                    for (int i = 0; i < mFriends.size(); i++) {
                        if (mFriends.get(i).isSelecte) {
                            uid = uid + mFriends.get(i).getId() + ",";
                            uhead = uhead + mFriends.get(i).getHeadUrl() + ",";

                        }
                    }
                }
                if (uid.length() > 0 && uid.endsWith(",")) {
                    uid = uid.substring(0, uid.length() - 1);
                }
                if (uhead.length() > 0 && uhead.endsWith(",")) {
                    uhead = uhead.substring(0, uhead.length() - 1);
                }
                Log.i(TAG, "onClick: selecteUid=" + uid);
                if (0 == type) {
                    MyAlertDialogManages.initShowCreatGroup(SelecteGroupFriendActivity.this, new MyAlertDialogManages.OnAlertOkSelectId() {
                        @Override
                        public void onOkClick(int whichButton, String content) {
                            switch (whichButton) {
                                case 0:
                                    createGroup(content);
                                    break;
                                case 1:
                                    showToast(getResources().getString(R.string.p_input_group));
                                    break;
                            }

                        }
                    });
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("uids", uid);
                    intent.putExtra("uheads", uhead);
                    setResult(-1, intent);
                    scrollToFinishActivity();
                }
                break;
        }
    }

    /**
     * 创建群组
     */
    private void createGroup(String name) {
        showProgress(null);
        final UserEntivity userEntivity = ToolsUtils.getUser();
        mPgService.createGroup(name, uid, userEntivity.getId() + "").subscribe(new AbsAPICallback<ImGroupEntivity>() {
            @Override
            public void onNext(ImGroupEntivity groupEntivity) {//建群成功后直接发起群聊
                groupEntivity.setCurrentid(userEntivity.getId());
                groupEntivity.setCreaterId(userEntivity.getId());
                groupEntivity.save();
                showToast(getResources().getString(R.string.create_group_success));
                hideProgress();
                Log.i(TAG, "onNext: goGroup=" + goGroup);
                if (goGroup == 1) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("groupSeri", groupEntivity);
                    bundle.putLong("groupid", groupEntivity.getId());
                    startActivity(ChatGroupActivity.class, bundle);
                   // setResult(Constant.MESSAGE_MAIN_GO_GROUP_RESULT);
                    scrollToFinishActivity();
//                    EventBus.getDefault().post(Constant.MESSAGE_MAIN_GO_GROUP);
                }else {
                    scrollToFinishActivity();
                }
            }

            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
                int code = ex.getCode();
                if (code == -5) {
                    ToolsUtils.showToast(SelecteGroupFriendActivity.this, getResources().getString(R.string.prompt_upgrade));
                }
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        //输入完毕
        String str = search_edit.getText().toString().trim();
        if (null != str && !"".equals(str.toString())) {
            mBFriends = new ArrayList<>();
            List<ImFriendEntivity> mBFriendsm = ImFriendEntivity.find(ImFriendEntivity.class, "currentid=? and is_black=?", ToolsUtils.getMyUserId(), "0");
            if (null != mBFriendsm && mBFriendsm.size() > 0) {
                for (int i = 0; i < mBFriendsm.size(); i++) {
                    try {
                        if (null!=mBFriendsm.get(i) && (mBFriendsm.get(i).getMobile().contains(str) || mBFriendsm.get(i).getRemark().contains(str) ||
                                mBFriendsm.get(i).getName().contains(str) || mBFriendsm.get(i).getNickName().contains(str))) {
                            mBFriends.add(mBFriendsm.get(i));
                        }
                    }catch (NullPointerException e){
                        e.printStackTrace();
                    }

                }
            }
            initData();
        }else {
            mBFriends = ImFriendEntivity.find(ImFriendEntivity.class, "currentid=? and is_black=?", ToolsUtils.getMyUserId(), "0");
            initData();
        }
    }
}
